﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using CustomControls.Dialog;
using CustomControls.InheritedFrameworkControls;
using CustomControls.MiscControls;
using CustomControls.PhotoViewer;
using CustomControls.PictureControl;
using Helpers;
using Infrasturcture.Global.Controls.Dialog;
using Infrasturcture.Global.Controls.LobbyMap;
using Infrasturcture.Global.Helpers.CustomHelpers.Events;
using Infrasturcture.TouchLibrary;
using MallInteractiveMap.ClientDataHandler;
using MallInteractiveMap.DTO;
using MallInteractiveMap.Language;
using TouchControls;
using WpfKb.Controls;
using TouchAction = TouchFramework.TouchAction;

namespace MallInteractiveMap
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Properties
        private readonly double _screenHeight = SystemParameters.PrimaryScreenHeight;
        private readonly double _screenWidth = SystemParameters.PrimaryScreenWidth;
        private FrameworkManger FrameworkManager { get; set; }
        protected MapPresenter MapPresenter { get; set; }
        public ObservableCollection<DTOFloor> Floors { get; set; }
        #endregion

        #region Dependancy Properties

        public string CurrentFloorTitle
        {
            get { return (string)GetValue(CurrentFloorTitleProperty); }
            set { SetValue(CurrentFloorTitleProperty, value); }
        }
        public static readonly DependencyProperty CurrentFloorTitleProperty =
            DependencyProperty.Register("CurrentFloorTitle", typeof(string), typeof(MainWindow));

        public string CurentTime
        {
            get { return (string)GetValue(TimeProperty); }
            set { SetValue(TimeProperty, value); }
        }

        public static readonly DependencyProperty TimeProperty =
            DependencyProperty.Register("CurentTime", typeof(string), typeof(MainWindow));



        public string CurrentDate
        {
            get { return (string)GetValue(CurrentDateProperty); }
            set { SetValue(CurrentDateProperty, value); }
        }

        public static readonly DependencyProperty CurrentDateProperty =
            DependencyProperty.Register("CurrentDate", typeof(string), typeof(MainWindow));


        public DTOFloor CurrentFloor
        {
            get { return (DTOFloor)GetValue(CurrentFloorProperty); }
            set { SetValue(CurrentFloorProperty, value); }
        }

        public static readonly DependencyProperty CurrentFloorProperty =
            DependencyProperty.Register("CurrentFloor", typeof(DTOFloor), typeof(MainWindow), new UIPropertyMetadata(null, OnCurrentFloorChanged));

        private FloatingTouchScreenKeyboard _keyboard;

        #endregion

        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
            Closing += MainWindowClosing;
            DataContext = this;
            FrameworkManager = new FrameworkManger(canvas);
            WaitScreen.WaitScreenBorder = WaitScreenBorder;
        }

        void MainWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            FrameworkManager.ShutDown();
        }

        private void PopulateUI()
        {
            List<DTOFloor> floors = null;
            try
            {
                floors = MapPresenter.GetFloors();
            }
            catch (Exception)
            {
                MessageBox.Show("Could not connect to database");
            }
            Floors = new ObservableCollection<DTOFloor>(floors);
            MallName.Text = MapPresenter.GetMall().Name;
            CurentTime = DateTime.Now.ToString("HH:mm");
            CurrentDate = DateTime.Today.ToString("dddd, MMMM dd, yyyy");
            SynchTime();
        }

        private void SynchTime()
        {
            new DispatcherTimer(new TimeSpan(0, 1, 0), DispatcherPriority.Normal, delegate
                                                                                      {
                                                                                          CurentTime = DateTime.Now.ToString("HH:mm");
                                                                                          CurrentDate = DateTime.Today.ToString("dddd, MMMM dd, yyyy");
                                                                                      }, Dispatcher);
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (ConfigurationManager.AppSettings["SetupDatabase"].Equals("true", StringComparison.OrdinalIgnoreCase))
            {
                DatabaseSetup();
            }
            InitializeCanvas();
            MapPresenter = new MapPresenter();
            PopulateUI();
            FrameworkManager.Initialize();
            LoadFloorList();
            RegisterSettingsButton();
            RegisterSearchBox();
            
        }

        private void DatabaseSetup()
        {
            WaitScreen.Show();
            new DatabaseSetup().InitializeDatabase();
            WaitScreen.Hide();
        }





        private void InitializeCanvas()
        {
            Width = _screenWidth;
            Height = _screenHeight;
            Left = 0;
            Top = 0;
            ResizeMode = ResizeMode.NoResize;
            WindowStyle = WindowStyle.None;
            WindowState = WindowState.Maximized;
        }

        private DialogViewer ShowDialog(IDialogContent content, Brush backgroundBrush = null)
        {
            var overlay = new Border
                              {
                                  Width = canvas.ActualWidth,
                                  Height = canvas.ActualHeight,
                                  Background = Brushes.Gray,
                                  Opacity = 0.2
                              };
            canvas.Children.Add(overlay);

            var dialogViewer = new DialogViewer(content) { Overlay = overlay };
            if (backgroundBrush != null)
            {
                dialogViewer.BackgroundBrush = backgroundBrush;
            }

            FrameworkManager.RegisterElement((IMTouchControl)dialogViewer, true, null);
            dialogViewer.CloseButton.Tag = FrameworkManager.RegisterElement(dialogViewer.CloseButton, false, new[] { TouchAction.Tap });

            Canvas.SetLeft(dialogViewer, 100);
            Canvas.SetTop(dialogViewer, 100);
            canvas.Children.Add(dialogViewer);
            dialogViewer.Closed += DialogViewerOnClosed;
            return dialogViewer;
        }

        private void ShowMessage(string title, string message)
        {
            var msg = new MTouchMessageBox(title, message);
            FrameworkManager.RegisterElement((IMTouchControl)msg, true, null);
            FrameworkManager.RegisterElement(msg.OkButton, false, new[] { TouchAction.Tap });
            Canvas.SetLeft(msg, canvas.ActualWidth / 5);
            Canvas.SetTop(msg, canvas.ActualHeight / 5);
            canvas.Children.Add(msg);
            msg.OkClick += MsgOkClick;
        }

        void MsgOkClick(object sender, EventArgs e)
        {
            var msg = sender as MTouchMessageBox;
            FrameworkManager.UnRegisterElement(msg.OkButton);
            FrameworkManager.RemoveControl(msg);
        }

        void DialogViewerOnClosed(object sender, EventArgs eventArgs)
        {
            var dialogViewer = sender as DialogViewer;
            if (dialogViewer != null)
            {
                canvas.Children.Remove(dialogViewer.Overlay);
                FrameworkManager.UnRegisterElement((IMTouchControl)dialogViewer);
            }
            FrameworkManager.UnRegisterElement(((IMTContainer)dialogViewer.CloseButton.Tag).Id);
            canvas.Children.Remove(dialogViewer);
        }

        private void AddPhoto(string filePath)
        {
            var pictureControl = new PictureControl();
            var i = pictureControl.SetImage(filePath);
            RenderOptions.SetBitmapScalingMode(i, BitmapScalingMode.HighQuality);
            FrameworkManager.RegisterElement((IMTouchControl)pictureControl, true, null);
            MapHolder.Children.Add(pictureControl);
        }
    }
}